package com.haocang.szgm.ui.report.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.LineChart;
import com.haocang.szgm.R;
import com.haocang.szgm.activity.comm.CommFinalActivity;
import com.haocang.szgm.requestcenter.DataModel;
import com.haocang.commonlib.network.interfaces.InitDataBeanBack;
import com.haocang.commonlib.network.interfaces.InitDataOneBeanBack;
import com.haocang.szgm.ui.floodpoint.activity.ShotShareUtil;
import com.haocang.szgm.ui.report.bean.CompositeIndexListBean;
import com.haocang.szgm.ui.report.bean.PurificationPlantDayBean;
import com.haocang.commonlib.curve.CompositeIndexBean;
import com.haocang.commonlib.curve.LineChartManager;
import com.haocang.szgm.utils.config.Config;
import com.haocang.szgm.utils.config.WebApi;
import com.haocang.szgm.utils.tools.CacheData;
import com.haocang.szgm.utils.tools.GetCommonParameters;
import com.haocang.szgm.utils.tools.MyTextUtils;

import net.tsz.afinal.annotation.view.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * ===============================================
 * 类 名 称：PurificationPlantDayActivity
 * 创建时间：2019/4/12 14:05
 * 编 写 人：ShenC
 * 类 说 明：水质净化厂日报表
 * ================================================
 * 修改内容：      修改时间：      修改人：
 * ===============================================
 */
public class PurificationPlantDayReadActivity extends CommFinalActivity {
    private String BillID;
    @ViewInject(id = R.id.mLineChart)
    LineChart mLineChart;
    @ViewInject(id = R.id.mLineChart_1)
    LineChart mLineChart_1;
    @ViewInject(id = R.id.sv_lin)
    ScrollView sv_lin;
    @ViewInject(id = R.id.iv_share)
    LinearLayout iv_share;
    @ViewInject(id = R.id.report_view_one_01)
    TextView report_view_one_01;
    @ViewInject(id = R.id.report_view_one_02)
    TextView report_view_one_02;
    @ViewInject(id = R.id.report_view_one_03)
    TextView report_view_one_03;
    @ViewInject(id = R.id.report_view_one_04)
    TextView report_view_one_04;
    @ViewInject(id = R.id.report_view_one_05)
    TextView report_view_one_05;
    @ViewInject(id = R.id.report_view_one_06)
    TextView report_view_one_06;
    @ViewInject(id = R.id.report_view_one_07)
    TextView report_view_one_07;
    @ViewInject(id = R.id.report_view_one_08)
    TextView report_view_one_08;
    @ViewInject(id = R.id.report_view_one_09)
    TextView report_view_one_09;
    @ViewInject(id = R.id.report_view_one_10)
    TextView report_view_one_10;
    @ViewInject(id = R.id.report_view_one_11)
    TextView report_view_one_11;
    @ViewInject(id = R.id.report_view_one_12)
    TextView report_view_one_12;
    @ViewInject(id = R.id.report_view_one_13)
    TextView report_view_one_13;
    @ViewInject(id = R.id.report_view_one_14)
    TextView report_view_one_14;
    @ViewInject(id = R.id.report_view_one_15)
    TextView report_view_one_15;
    @ViewInject(id = R.id.tv_YL_01)
    TextView tv_YL_01;
    @ViewInject(id = R.id.tv_YL_02)
    TextView tv_YL_02;

    @ViewInject(id = R.id.report_view_two_01)
    TextView report_view_two_01;
    @ViewInject(id = R.id.report_view_two_02)
    TextView report_view_two_02;
    @ViewInject(id = R.id.report_view_two_03)
    TextView report_view_two_03;
    @ViewInject(id = R.id.report_view_two_04)
    TextView report_view_two_04;
    @ViewInject(id = R.id.report_view_two_05)
    TextView report_view_two_05;
    @ViewInject(id = R.id.report_view_two_06)
    TextView report_view_two_06;
    @ViewInject(id = R.id.report_view_two_07)
    TextView report_view_two_07;
    @ViewInject(id = R.id.report_view_two_08)
    TextView report_view_two_08;
    @ViewInject(id = R.id.report_view_two_09)
    TextView report_view_two_09;
    @ViewInject(id = R.id.report_view_two_10)
    TextView report_view_two_10;
    @ViewInject(id = R.id.report_view_two_11)
    TextView report_view_two_11;
    @ViewInject(id = R.id.report_view_two_12)
    TextView report_view_two_12;
    @ViewInject(id = R.id.report_view_two_13)
    TextView report_view_two_13;
    @ViewInject(id = R.id.report_view_two_14)
    TextView report_view_two_14;
    @ViewInject(id = R.id.report_view_two_15)
    TextView report_view_two_15;
    @ViewInject(id = R.id.report_view_Memo)
    TextView report_view_Memo;
    @ViewInject(id = R.id.report_view_PumpLevelAverage)
    TextView report_view_PumpLevelAverage;


    @ViewInject(id = R.id.new_report_view_one_01)
    TextView new_report_view_one_01;
    @ViewInject(id = R.id.new_report_view_one_02)
    TextView new_report_view_one_02;


    @ViewInject(id = R.id.tv_titiename)
    TextView tv_titiename;


    private LineChartManager lineChartManager;
    private LineChartManager lineChartManager1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
        initEvent();

        if (CacheData.PurificationPlantReadDay_UPDATE) {
            initData();
        } else {
            ToastShow("无报表数据");
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        if (BillID != null) {
            initData();
        }
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_purification_plant_day_read;
    }

    @Override
    protected boolean showNavigation() {
        return true;
    }

    @Override
    protected int showMoreIcon() {
        return R.drawable.ic_edit_white;
    }

    @Override
    protected String showTitleName() {
        return "光明水质净化厂报表";
    }


    private void initView() {
        BillID = getIntent().getStringExtra("ID");
    }


    private void initEvent() {
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });


        iv_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PurificationPlantDayReadActivity.this, PurificationPlantDayEditActivity.class);
                CacheData.PurificationPlantDay_UPDATE = true;
                intent.putExtra("ID", BillID);
                startActivity(intent);
            }
        });

        iv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShotShareUtil.scrollViewScreenShot(PurificationPlantDayReadActivity.this, sv_lin, "szgm_share_"+System.currentTimeMillis());
                //ShotShareUtil.sharePic(PurificationPlantDayReadActivity.this);

            }
        });

        tv_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseTime();
            }
        });

    }


    private void initData() {
        String ApiUrl = Config.host
                + WebApi.Api_GetPurificationPlantDay
                + "GetDetail?ID=" + BillID;
        Log.d("请求曲线", "数据:" + ApiUrl);
        DataModel.GetApiRequestOneMode("PurificationPlantDayBean", ApiUrl, new InitDataOneBeanBack<PurificationPlantDayBean>() {
            @Override
            public void callbak(boolean b, PurificationPlantDayBean data, String msg) {
                if (b) {
                    showData(data);
                    tv_name.setText("光明水质净化厂报表(" + MyTextUtils.toYMD(data.getCreateDT()) + ")");
                    tv_titiename.setText("光明水质净化厂报表(" + MyTextUtils.toYMD(data.getCreateDT()) + ")");
                } else {
                    ToastShow(msg);
                }

            }
        });
    }


    private void initData(String DT) {
        String ApiUrl = Config.host
                + WebApi.Api_GetPurificationPlantDay
                + "GetDetailByDT?DT=" + DT;
        Log.d("请求曲线", "请求url:" + ApiUrl);
        DataModel.GetApiRequestMode("PurificationPlantDayBean", ApiUrl, new InitDataBeanBack<PurificationPlantDayBean>() {
            @Override
            public void callbak(boolean b, List<PurificationPlantDayBean> list, String msg) {
                if (b) {
                    if (list == null || list.size() == 0) {
                        ToastShow("您选择的日期没有报表数据！");
                    } else {
                        showData(list.get(0));
                        tv_name.setText("光明水质净化厂报表(" + MyTextUtils.toYMD(list.get(0).getCreateDT()) + ")");
                        tv_titiename.setText("光明水质净化厂报表(" + MyTextUtils.toYMD(list.get(0).getCreateDT()) + ")");
                    }
                } else {
                    ToastShow(msg);
                }
            }
        });


    }

    /**
     * ===============================================
     * 创建时间：2019/4/15 10:33
     * 编 写 人：ShenC
     * 方法说明：报表数据展示，
     * ================================================
     * 修改内容：      修改时间：      修改人：
     * ===============================================
     */
    private void showData(PurificationPlantDayBean data) {
        try {

            BillID = data.getID();

            if (data.getHandleAmount1() != null) {
                report_view_one_01.setText(data.getHandleAmount1() + "吨");
                double d = (Double.valueOf(data.getHandleAmount1()) / 300000) * 100;
                d = MyTextUtils.ToTwoplaceDouble(d);
                report_view_one_02.setText(d + "%");
            }

//            report_view_one_03.setText(data.getEffluent_1_Mud() + "吨(" + data.getEffluent_1_MudWater() + "%)");
//            report_view_one_01.setText(data.getTotalJSL1() + "吨");
            double d = (Double.valueOf(data.getTotalJSL1()) / 150000) * 100;
            d = MyTextUtils.ToTwoplaceDouble(d);
            new_report_view_one_01.setText(data.getTotalJSL1() + "(" + d + "%)");

            double e = (Double.valueOf(data.getTotalJSL2()) / 150000) * 100;
            e = MyTextUtils.ToTwoplaceDouble(e);
            new_report_view_one_02.setText(data.getTotalJSL2() + "(" + e + "%)");

            report_view_one_04.setText(data.getInletCOD());
            report_view_one_05.setText(data.getEffluent_1_COD());
            report_view_one_06.setText(data.getInletNH3());
            report_view_one_07.setText(data.getEffluent_1_NH3());
            report_view_one_08.setText(data.getInletTN());
            report_view_one_09.setText(data.getEffluent_1_TN());
            report_view_one_10.setText(data.getInletTP());
            report_view_one_11.setText(data.getEffluent_1_TP());
            report_view_one_12.setText(data.getInletSS());
            report_view_one_13.setText(data.getEffluent_1_SS());
            report_view_one_14.setText(data.getInletPH());
            report_view_one_15.setText(data.getEffluent_1_PH());

            if (data.getHandleAmount2() != null) {
                report_view_two_01.setText(data.getHandleAmount2() + "吨");
                double d2 = (Double.valueOf(data.getHandleAmount2()) / 150000) * 100;
                d2 = MyTextUtils.ToTwoplaceDouble(d2);
                report_view_two_02.setText(d2 + "%");
            }
            report_view_two_03.setText(data.getEffluent_2_Mud() + "吨(" + data.getEffluent_2_MudWater() + "%)");

            report_view_two_04.setText(data.getInletCOD());
            report_view_two_05.setText(data.getEffluent_2_COD());
            report_view_two_06.setText(data.getInletNH3());
            report_view_two_07.setText(data.getEffluent_2_NH3());
            report_view_two_08.setText(data.getInletTN());
            report_view_two_09.setText(data.getEffluent_2_TN());
            report_view_two_10.setText(data.getInletTP());
            report_view_two_11.setText(data.getEffluent_2_TP());
            report_view_two_12.setText(data.getInletSS());
            report_view_two_13.setText(data.getEffluent_2_SS());
            report_view_two_14.setText(data.getInletPH());
            report_view_two_15.setText(data.getEffluent_2_PH());
            report_view_Memo.setText(data.getMemo());

            //余氯 :进水/出水
            tv_YL_01.setText(data.getInletYL());
            tv_YL_02.setText(data.getEffluent_1_YL());

            //显示泵坑液位曲线
            mLineChart.clear();
            lineChartManager = new LineChartManager(mLineChart);
            List<CompositeIndexBean> pump_list = new ArrayList<>();
            pump_list.add(new CompositeIndexBean("00:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel0())));
            pump_list.add(new CompositeIndexBean("04:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel4())));
            pump_list.add(new CompositeIndexBean("08:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel8())));
            pump_list.add(new CompositeIndexBean("12:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel12())));
            pump_list.add(new CompositeIndexBean("16:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel16())));
            pump_list.add(new CompositeIndexBean("20:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel20())));


            int k = 0;
            double pump_level_sum = 0;
            if (!MyTextUtils.IsNullByString(data.getPumpLevel0())) {
                pump_level_sum += MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel0());
                k++;
            }
            if (!MyTextUtils.IsNullByString(data.getPumpLevel4())) {
                pump_level_sum += MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel4());
                k++;
            }
            if (!MyTextUtils.IsNullByString(data.getPumpLevel8())) {
                pump_level_sum += MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel8());
                k++;
            }
            if (!MyTextUtils.IsNullByString(data.getPumpLevel12())) {
                pump_level_sum += MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel12());
                k++;
            }
            if (!MyTextUtils.IsNullByString(data.getPumpLevel16())) {
                pump_level_sum += MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel16());
                k++;
            }
            if (!MyTextUtils.IsNullByString(data.getPumpLevel20())) {
                pump_level_sum += MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel20());
                k++;
            }
            String numStr = "平均液位：" + MyTextUtils.ToTwoplaceDouble(pump_level_sum / k) + "m";
            report_view_PumpLevelAverage.setText(numStr + getResources().getString(R.string.median_str) + data.Median + "m");

            lineChartManager.showLineChartPumpReport(pump_list, "泵坑液位", getResources().getColor(R.color.app_title_color));
            Drawable drawable = getResources().getDrawable(R.drawable.fade_blue);
            lineChartManager.setChartFillDrawable(drawable);//填充数据曲线
            lineChartManager.setReportMarkerView(PurificationPlantDayReadActivity.this);


            mLineChart_1.clear();
            lineChartManager1 = new LineChartManager(mLineChart_1);
            List<CompositeIndexBean> pump_list1 = new ArrayList<>();
            pump_list1.add(new CompositeIndexBean("00:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel0())));
            pump_list1.add(new CompositeIndexBean("04:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel4())));
            pump_list1.add(new CompositeIndexBean("08:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel8())));
            pump_list1.add(new CompositeIndexBean("12:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel12())));
            pump_list1.add(new CompositeIndexBean("16:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel16())));
            pump_list1.add(new CompositeIndexBean("20:00", MyTextUtils.StringToTwoplaceDouble(data.getPumpLevel20())));


            String ApiUrl = Config.host
                    + WebApi.Api_GetPurificationPlantDay
                    + "GetSewageWater?DataDT=" + GetCommonParameters.ConverToDateToString(data.getCreateDT(), 0);


            DataModel.GetApiRequestMode("CompositeIndexListBean", ApiUrl, new InitDataBeanBack<CompositeIndexListBean>() {
                @Override
                public void callbak(boolean b, List<CompositeIndexListBean> list, String msg) {
                    if (b) {

                        if (list.get(0).getData() != null && list.get(0).getData().size() > 0) {
                            float fi_max = GetYLimitValue("MAX", list.get(0).getData(), list.get(2).getData());
                            float fi_min = GetYLimitValue("MIN", list.get(0).getData(), list.get(2).getData());
                            lineChartManager1.showLineChartReport(list.get(0).getData(), list.get(0).getName(), getResources().getColor(R.color.app_title_color), fi_min, fi_max);
                            lineChartManager1.addLine2(list.get(2).getData(), list.get(2).getName(), getResources().getColor(R.color.greenyellow));
                            lineChartManager1.setReportMarkerView(PurificationPlantDayReadActivity.this);
                        }

                    }
                }
            });


            //显示颜色
            ChangeBgColor(report_view_one_01, data.getHandleAmount1(), 180000, 240000, 300000);
            ChangeBgColor(report_view_two_01, data.getHandleAmount2(), 180000, 240000, 300000);

            ChangeBgColor(report_view_one_04, data.getInletCOD(), 350);
            ChangeBgColor(report_view_two_04, data.getInletCOD(), 350);
            ChangeBgColor(report_view_one_05, data.getEffluent_1_COD(), 30);
            ChangeBgColor(report_view_two_05, data.getEffluent_2_COD(), 30);

            ChangeBgColor(report_view_one_07, data.getEffluent_1_NH3(), 1.5);
            ChangeBgColor(report_view_two_07, data.getEffluent_2_NH3(), 1.5);
            ChangeBgColor(report_view_one_06, data.getInletNH3(), 40);
            ChangeBgColor(report_view_two_06, data.getInletNH3(), 40);

            ChangeBgColor(report_view_one_08, data.getInletTN(), 45);
            ChangeBgColor(report_view_two_08, data.getInletTN(), 45);
            ChangeBgColor(report_view_one_09, data.getEffluent_1_TN(), 10);
            ChangeBgColor(report_view_two_09, data.getEffluent_2_TN(), 10);

            ChangeBgColor(report_view_one_10, data.getInletTP(), 8);
            ChangeBgColor(report_view_two_10, data.getInletTP(), 8);
            ChangeBgColor(report_view_one_11, data.getEffluent_1_TP(), 0.3);
            ChangeBgColor(report_view_two_11, data.getEffluent_2_TP(), 0.3);

            if (data.getInletSS() != null) {

                String inletss = data.getInletSS();
                //如果找到了小于
                if (data.getInletSS().indexOf("<") > -1 || data.getInletSS().indexOf(">") > -1) {
                    inletss = inletss.replaceAll("<", "");
                    inletss = inletss.replaceAll(">", "");
                }

                ChangeBgColor(report_view_one_12, inletss, 300);
                ChangeBgColor(report_view_two_12, inletss, 300);
            }


            if (data.getEffluent_1_SS() != null) {

                String inletss = data.getEffluent_1_SS();
                //如果找到了小于
                if (inletss.indexOf("<") > -1 || inletss.indexOf(">") > -1) {
                    inletss = inletss.replaceAll("<", "");
                    inletss = inletss.replaceAll(">", "");
                }
                ChangeBgColor(report_view_one_13, inletss, 10);
            }
            if (data.getEffluent_2_SS() != null) {

                String inletss = data.getEffluent_2_SS();
                //如果找到了小于
                if (inletss.indexOf("<") > -1 || inletss.indexOf(">") > -1) {
                    inletss = inletss.replaceAll("<", "");
                    inletss = inletss.replaceAll(">", "");
                }
                ChangeBgColor(report_view_two_13, inletss, 10);
            }


            ChangeBgColor(report_view_one_14, data.getInletPH(), 6, 9);
            ChangeBgColor(report_view_one_15, data.getEffluent_1_PH(), 6, 9);
            ChangeBgColor(report_view_two_14, data.getInletPH(), 6, 9);
            ChangeBgColor(report_view_two_15, data.getEffluent_2_PH(), 6, 9);


        } catch (Exception e) {
            ToastShow(e.toString());
        }

    }


    /**
     * 方法说明：根据限制值设置背景颜色
     */
    private void ChangeBgColor(TextView tv, String str_value, double limit) {
        try {
            double valus = Double.valueOf(str_value);
            tv.setBackgroundResource(valus > limit ? R.color.bg_table_r : R.color.bg_table_w);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void ChangeBgColor(TextView tv, String str_value, double min, double max) {
        try {
            double valus = Double.valueOf(str_value);
            tv.setBackgroundResource((min <= valus && valus <= max) ? R.color.bg_table_w : R.color.bg_table_r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void ChangeBgColor(TextView tv, String str_value, double a, double b, double c) {
        try {
            double valus = Double.valueOf(str_value);
            if (valus < a) {
                tv.setBackgroundResource(R.color.bg_table_r);
            } else if (valus >= a && valus <= b) {
                tv.setBackgroundResource(R.color.bg_table_y);
            } else {
                tv.setBackgroundResource(R.color.bg_table_w);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 方法说明：比较过去2个数组的最大值和最小值
     */
    private float GetYLimitValue(final String type, final List<CompositeIndexBean> dataList1, final List<CompositeIndexBean> dataList2) {

        try {
            //根据数据dataList找出最大值和最小值
            float min = 0;
            float max = 0;
            if (dataList1.size() > 0) {
                min = (float) dataList1.get(0).getRate();
                max = (float) dataList1.get(0).getRate();
            }
            for (int i = 0; i < dataList1.size(); i++) {
                CompositeIndexBean data = dataList1.get(i);
                if (min > data.getRate()) {
                    min = (float) data.getRate();
                }
                if (max < data.getRate()) {
                    max = (float) data.getRate();
                }
            }

            //根据数据dataList找出最大值和最小值
            float min1 = 0;
            float max1 = 0;
            if (dataList2.size() > 0) {
                min1 = (float) dataList2.get(0).getRate();
                max1 = (float) dataList2.get(0).getRate();
            }
            for (int i = 0; i < dataList2.size(); i++) {
                CompositeIndexBean data = dataList2.get(i);
                if (min1 > data.getRate()) {
                    min1 = (float) data.getRate();
                }
                if (max1 < data.getRate()) {
                    max1 = (float) data.getRate();
                }
            }

            if (type.equals("MAX")) {
                if (max > max1) {
                    return max;
                } else {
                    return max1;
                }
            } else {
                if (min < min1) {
                    return min;
                } else {
                    return min1;
                }
            }
        } catch (Exception e) {
            if (type.equals("MAX")) {
                return 10f;
            } else {
                return -1f;
            }
        }
    }


    private void chooseTime() {
        TimePickerView.Builder builder = new TimePickerView.Builder(PurificationPlantDayReadActivity.this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(java.util.Date date, View v) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String time = MyTextUtils.date2String(date, simpleDateFormat);
                // tv_name.setText("水质净化厂日报表("+time+")");
                initData(time);
            }
        });
        builder.setType(new boolean[]{true, true, true, false, false, false});
        TimePickerView pvTime = builder.build();
        pvTime.setDate(Calendar.getInstance());
        pvTime.show();
    }

    //退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            return super.onKeyDown(keyCode, event);
        } else {
            return false;
        }
    }

}
